package com.luoxiang.socialandroid.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.RelativeLayout;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.just.agentweb.AgentWeb;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.base.BaseActivity;

public class WebContentActivity extends BaseActivity {
    private AgentWeb mWv;
    private ConstraintLayout constraintView;

    @Override
    protected void initListener() {

    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_web_content);
        constraintView = findViewById(R.id.constraintView);

    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        String h5url = intent.getStringExtra("h5url");
        mWv = AgentWeb.with(WebContentActivity.this)
                .setAgentWebParent(constraintView, new RelativeLayout.LayoutParams(-1, -1)) //-1是指父布局
                .useDefaultIndicator()
                .createAgentWeb()
                .ready()
                .go(h5url);
        mWv.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface());
    }


    @Override
    protected void onResume() {
        super.onResume();
    }


    public boolean shouldOverrideUrlLoading(final WebView view, String url) {
        // 获取上下文, H5PayDemoActivity为当前页面
        final Activity context = WebContentActivity.this;
        // ------  对alipays:相关的scheme处理 -------
        if (url.startsWith("alipays:") || url.startsWith("alipay")) {
            try {
                context.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
            } catch (Exception e) {
                new AlertDialog.Builder(context)
                        .setMessage(R.string.mi_weianzhuangzhifubao)
                        .setPositiveButton(R.string.mi_lijianzhuang, (dialog, which) -> {
                            Uri alipayUrl = Uri.parse("https://d.alipay.com");
                            context.startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                        }).setNegativeButton(getString(R.string.mi_quxiao), null).show();
            }
            return true;
        }
        // ------- 处理结束 -------
        if (!(url.startsWith("http") || url.startsWith("https"))) {
            return true;
        }
        view.loadUrl(url);
        return true;
    }

    public class AndroidInterface {
        @JavascriptInterface
        public void callAndroid() {
            finish();
        }
    }

}